package com.qq.controller;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Random;

@Controller
@RequestMapping("/code")
public class SendCodeController {

    @Autowired
    private JavaMailSender mailSender;

    @PostMapping("/sendCode")
    @ResponseBody
    public String sendCode(@RequestParam String email, HttpSession session) {
        // 生成6位验证码
        String code = generateVerificationCode();
        session.setAttribute("emailCode", code);

        try {
            // 发送验证码邮件
            sendVerificationEmail(email, code);
            return "验证码发送成功";
        } catch (MessagingException e) {
            e.printStackTrace();
            return "验证码发送失败";
        }
    }

    private String generateVerificationCode() {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            code.append(random.nextInt(10));
        }
        return code.toString();
    }

    private void sendVerificationEmail(String to, String code) throws MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

        helper.setSubject("您的验证码");
        helper.setText("<h2>您好，您的验证码是：" + code + "</h2><p>请勿泄露给他人。</p><p>5分钟内有效。</p>", true);
        helper.setTo(to);
        helper.setFrom("asrtyjjfghjk@qq.com");  // 替换为你自己的邮箱

        mailSender.send(mimeMessage);
    }

}
